"""


"""
from django.db import connection

class DBUtils:

    @classmethod
    def get_connection(cls):
        """
        获取数据库的连接对象
        """
        return connection

    @classmethod
    def insert(cls, sql: str, args=None):
        # 获取 连接 
        conn = cls.get_connection()
        with conn.cursor() as cursor:
            # 执行SQL、并获取影响的行数
            rows = cursor.execute(sql, args)
            assert rows == 1, f"插入数据期待影响 1 行, 实际影响{rows}行"
            return cursor.lastrowid

    def insert_many(cls, sql: str, args=None):
        # 获取 连接 
        conn = cls.get_connection()
        with conn.cursor() as cursor:
            # 执行SQL、并获取影响的行数
            rows = cursor.executemany(sql, args)
            assert rows == len(args), f"插入数据期待影响 {len(args)} 行, 实际影响{rows}行"
            return rows

    @classmethod
    def update(cls, sql: str, args=None):
        """
        更新
        """
        conn = cls.get_connection()
        with conn.cursor() as cursor:
            # 执行SQL、并获取影响的行数
            return cursor.execute(sql, args)

    @classmethod
    def delete(cls, sql: str, args=None):
        """ 
        删除
        """
        return cls.update(sql, args)

    @classmethod
    def select_one(cls, sql, args=None):
        """
        查询单条数据
        """
        conn = cls.get_connection()
        with conn.cursor() as cursor:
            # 执行SQL、并获取影响的行数
            rows = cursor.execute(sql, args) 
            if rows > 1:
                raise Exception(f"select_one 方法 期待 1 条数据、实际返回 {rows} 条")

            if rows == 1:
                # 获取 查询的数据 和查询的列 
                data = cursor.fetchone()
                columns = [col[0] for col in cursor.description]
                return dict(zip(columns, data))

    @classmethod
    def select_all(cls, sql, args=None):
        """
        查询多条数据
        """
        conn = cls.get_connection()
        with conn.cursor() as cursor:
            # 执行SQL、并获取影响的行数
            cursor.execute(sql, args) 
            # 获取 查询到的所有数据
            data = cursor.fetchall()
            columns = [col[0] for col in cursor.description]
            return [dict(zip(columns, d))  for d in data]
